package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.entity.Result;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.exception.ConsumerException;
import com.itheima.ydd.service.YddUserService;
import com.itheima.ydd.utils.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@RestController
@Slf4j
@RequestMapping("/home/index")
public class IndexControllerQ {
    @Autowired
    YddUserService service;
    @Autowired
    private YddUserService yddUserService;


    @PostMapping("/login")
    public ResponseEntity<Result> login(@RequestBody YddUser user) {
        LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddUser::getMobile, user.getMobile());
        YddUser user1 = service.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(user1)) {
            throw new ConsumerException("该用户不存在");
        }
        String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        if (!user1.getPassword().equals(password)) {
            throw new ConsumerException("该用户不存在");
        }

        Map tokenMap = new HashMap<>();
        tokenMap.put("id", user1.getId());
        String token = AppJwtUtil.getToken(tokenMap);
        HashMap<String, String> map = new HashMap<>();
        map.put("token", token);
        return ResponseEntity.ok(new Result(0, "登录成功", map));

    }
}